/*
** Zabbix
** Copyright (C) 2001-2023 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/

package yashandb

import (
	"context"
	"fmt"
	"strings"

	"git.zabbix.com/ap/plugin-support/zbxerr"
)

const (
	temp          = "TEMPORARY"
	perm          = "PERMANENT"
	undo          = "UNDO"
	defaultPERMTS = "USERS"
	defaultTEMPTS = "TEMP"
)

func tablespacesHandler(ctx context.Context, conn YasClient, params map[string]string,
	_ ...string) (interface{}, error) {
	var tablespaces string

	query, err := getQuery(params)
	if err != nil {
		return nil, err
	}

	row, err := conn.QueryRow(ctx, query)
	if err != nil {
		return nil, zbxerr.ErrorCannotFetchData.Wrap(err)
	}

	err = row.Scan(&tablespaces)
	if err != nil {
		return nil, zbxerr.ErrorCannotFetchData.Wrap(err)
	}

	// Add leading zeros for floats: ".03" -> "0.03".
	// YashanDB JSON functions are not RFC 4627 compliant.
	// There should be a better way to do that, but I haven't come up with it ¯\_(ツ)_/¯
	tablespaces = strings.ReplaceAll(tablespaces, "\":.", "\":0.")

	return tablespaces, nil
}

func getQuery(params map[string]string) (string, error) {
	ts := params["Tablespace"]
	t := params["Type"]

	if ts == "" && t == "" {
		return getFullQuery(), nil
	}

	var err error
	ts, t, err = prepValues(ts, t)
	if err != nil {
		return "", zbxerr.ErrorInvalidParams.Wrap(err)
	}

	var query string

	switch t {
	case perm, undo:
		query = getPermQueryPart(ts)
	case temp:
		query = getTempQueryPart(ts)
	default:
		return "", zbxerr.ErrorInvalidParams.Wrap(fmt.Errorf("incorrect table-space type %s", t))
	}

	return query, nil
}

func prepValues(ts, t string) (outTableSpace string, outType string, err error) {
	if ts != "" && t != "" {
		return ts, t, nil
	}

	if ts == "" {
		if t == perm {
			return defaultPERMTS, t, nil
		}

		if t == temp {
			return defaultTEMPTS, t, nil
		}

		return "", "", fmt.Errorf("incorrect type %s", t)
	}

	return ts, perm, nil
}

func getFullQuery() string {
	return `
select '['||LISTAGG('{"' || TABLESPACE_NAME || '":{"contents":"' || CONTENTS || '","file_bytes":' || BYTES || ',"max_bytes":' || MAXBYTES || ',"free_bytes":' || free_bytes || ',"used_bytes":' || USER_BYTES || ',"used_pct_max":' || ROUND(USER_BYTES / MAXBYTES * 100, 2) ||',"used_file_pct":'|| ROUND(USER_BYTES / BYTES * 100, 2) ||',"status":'||STATUS||'}}',',')||']'
from
(
SELECT  
        dt.TABLESPACE_NAME,
        dt.CONTENTS ,
        sum(ddf.BYTES) BYTES,
        DECODE(sum(ddf.MAXBYTES),0,sum(ddf.USER_BYTES),sum(ddf.MAXBYTES))  MAXBYTES,
        sum(ddf.BYTES) - sum(ddf.USER_BYTES) free_bytes,
        sum(ddf.USER_BYTES) USER_BYTES,
        decode(dt.STATUS,'ONLINE',1,0)STATUS
FROM    
        DBA_DATA_FILES ddf ,
        DBA_TABLESPACES dt
WHERE   
        DDF.TABLESPACE_NAME = dt.TABLESPACE_NAME
GROUP BY dt.TABLESPACE_NAME,dt.CONTENTS,dt.STATUS
)
`
}

func getPermQueryPart(name string) string {
	fmt.Println(name)
	return fmt.Sprintf(`
select '['||LISTAGG('{"' || TABLESPACE_NAME || '":{"contents":"' || CONTENTS || '","file_bytes":' || BYTES || ',"max_bytes":' || MAXBYTES ||',"free_bytes":' || free_bytes || ',"used_bytes":' || USER_BYTES || ',"used_pct_max":' || ROUND(USER_BYTES / MAXBYTES * 100, 2) ||',"used_file_pct":'|| ROUND(USER_BYTES / BYTES * 100, 2) ||',"status":'||STATUS||'}}',',')||']'
from
(
SELECT
        dt.TABLESPACE_NAME,
        dt.CONTENTS ,
        sum(ddf.BYTES) BYTES,
        DECODE(sum(ddf.MAXBYTES),0,sum(ddf.USER_BYTES),sum(ddf.MAXBYTES))  MAXBYTES,
        sum(ddf.BYTES) - sum(ddf.USER_BYTES) free_bytes,
        sum(ddf.USER_BYTES) USER_BYTES,
        decode(dt.STATUS,'ONLINE',1,0)STATUS
FROM
        DBA_DATA_FILES ddf ,
        DBA_TABLESPACES dt
WHERE
        DDF.TABLESPACE_NAME = dt.TABLESPACE_NAME
        AND dt.TABLESPACE_NAME = '%s'
GROUP BY dt.TABLESPACE_NAME,dt.CONTENTS,dt.STATUS
)
`, name)
}

func getTempQueryPart(name string) string {
	return fmt.Sprintf(`
select '['||LISTAGG('{"' || TABLESPACE_NAME || '":{"contents":"' || CONTENTS || '","file_bytes":' || BYTES || ',"max_bytes":' || MAXBYTES || ',"free_bytes":' || free_bytes || ',"used_bytes":' || USER_BYTES || ',"used_pct_max":' || ROUND(USER_BYTES / MAXBYTES * 100, 2) ||',"used_file_pct":'|| ROUND(USER_BYTES / BYTES * 100, 2) ||',"status":'||STATUS||'}}',',')||']'
from
(
SELECT  
        dt.TABLESPACE_NAME,
        dt.CONTENTS ,
        sum(ddf.BYTES) BYTES,
        DECODE(sum(ddf.MAXBYTES),0,sum(ddf.USER_BYTES),sum(ddf.MAXBYTES))  MAXBYTES,
        sum(ddf.BYTES) - sum(ddf.USER_BYTES) free_bytes,
        sum(ddf.USER_BYTES) USER_BYTES,
        decode(dt.STATUS,'ONLINE',1,0)STATUS
FROM    
        DBA_TEMP_FILES ddf ,
        DBA_TABLESPACES dt
WHERE   
        DDF.TABLESPACE_NAME = dt.TABLESPACE_NAME
AND dt.TABLESPACE_NAME = '%s'
GROUP BY dt.TABLESPACE_NAME,dt.CONTENTS,dt.STATUS
    )`, name)
}
